import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import fs from "fs";
import path from "path";
// import zipDir from "rollup-plugin-zipdir";
import packageJson from "./package.json";

const PROXY_API_URL="http://192.168.1.11:8081/";
const BASE_PATH = "/";

let profile = process.env.BUILD_PROFILE;
let production = process.env.NODE_ENV === "production";
let version = null;
let date = new Date().toLocaleDateString().replace(/\//g, "-");

if (!fs.existsSync("build")) fs.mkdirSync("build");

const buildInfoPlugin = BuildInfoPlugin();
const plugins = [vue() /* , buildInfoPlugin */];

if (production) {
	// plugins.push(
	// 	zipDir({
	// 		name: `front-web_v${buildInfoPlugin.versionContent}`,
	// 		outputDir: "build",
	// 	})
	// );
}

// if (profile) {
// 	plugins.splice(2, 0,
// 		copy({
// 			targets: [
// 				{ src: "profiles/" + profile + "/**", dest: 'dist/' }
// 			], // 路径
// 			hook: 'writeBundle', // 钩子，插件运行在rollup完成打包并将文件写入磁盘之前
// 			verbose: true // 在终端进行console.log
// 		})
// 	);
// }

// https://vitejs.dev/config/
export default defineConfig({
	plugins,
	build: {
		sourcemap: true,
	},
	base: BASE_PATH,
	define: {
		BUILD_DATE: `"${buildInfoPlugin.date}"`,
		BUILD_VERSION: `"${buildInfoPlugin.version}"`,
		BUILD_PROFILE: `"${buildInfoPlugin.profile}"`,
		BASE_PATH: `"${buildInfoPlugin.basePath}"`,
	},
	resolve: {
		alias: {
			"@": path.resolve(__dirname, "./src"),
		},
	},
	css: {
		preprocessorOptions: {
			less: {
				javascriptEnabled: true,
			},
		},
	},
	server: {
		proxy: {},
	},
});

function getVersion() {
	if (production) {
		packageJson.versionCode++;
	}
	fs.writeFileSync("./package.json", JSON.stringify(packageJson, null, 2));
	return packageJson;
}

function BuildInfoPlugin() {
	let name = "BuildInfoPlugin";

	let ver = getVersion();
	let versionContent = ver.version + "(" + ver.versionCode + ")";
	version = versionContent;

	let configFile = "public/profile.js";
	if (profile) {
		configFile = `profiles/${profile}/profile.js`;
	}
	let configContent =
		`var BUILD_DATE = "${date}";
	var BUILD_VERSION = "${version}";
	var BUILD_PROFILE = "${profile}";
	var BASE_PATH = "${BASE_PATH}";\n\n` + fs.readFileSync(configFile);

	return {
		name,
		date,
		version,
		profile,
		basePath: BASE_PATH,
		versionContent,
		generateBundle() {
			this.emitFile({
				type: "asset",
				fileName: "version",
				source: versionContent,
			});
			this.emitFile({
				type: "asset",
				fileName: "config.js",
				source: configContent,
			});
		},
		writeBundle() {},
	};
}
